<template>
  <div>
    <el-tree
      ref="tree"
      default-expand-all
      :data="treeData"
      :props="{'label':'name'}"
      node-key="id"
      show-checkbox
      check-strictly
    />
    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionListAPI } from '@/api/permission'
import { getRoleIdAPI, assignPermAPI } from '@/api/setting'
import { transTreeD } from '@/utils'
export default {
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      treeData: [], // 权限点列表
      permIds: [] // 当前角色权限
    }
  },
  created() {
    this.getPermissionListFn()
    this.getRoleIdFn()
  },
  methods: {
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 确定按钮
    async  setRolesBtn() {
    // 获取到当前所选的权限点
      this.permIds = this.$refs.tree.getCheckedKeys()
      // 调用接口更新角色权限
      await assignPermAPI({ id: this.roleId, permIds: this.permIds })
      this.$emit('close')
    },

    // 获取权限点列表的方法
    async getPermissionListFn() {
      const res = await getPermissionListAPI()
      this.treeData = transTreeD(res.data, '0')
    },

    // 获取角色详情,为了获取到当前角色的权限点,树形组件回填
    async getRoleIdFn() {
      const res = await getRoleIdAPI(this.roleId)
      this.permIds = res.data.permIds
      // 树形组件已选回填
      this.$refs.tree.setCheckedKeys(this.permIds)
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
